package cn.cboard.gateway;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @author 
 *
 * Utility class for common persistence functions
 */
public abstract class DAOUtil {

	/**
	 * Get a connection
	 * 
	 * 
	 * This code to be replaced with however you derive your datasource!!!!
	 */
	public static Connection getConnection() throws DAOException {

		try {

			PropertyUtil props =
				PropertyUtil.get(
					"au.com.ldabreo.persistence.dao.datasource",
					"mysql");
			// load driver
			Class.forName(props.getAsString("driver")).newInstance();

			String username = props.getAsString("user.name");
			String password = props.getAsString("user.password");
			String url = props.getAsString("db.url");

			Connection conn = null;

			if (username != null && password != null)
				conn = DriverManager.getConnection(url, username, password);
			else
				conn = DriverManager.getConnection(url);

			return conn;

		} catch (Exception e) {
			throw new DAOException(
				"Could not obtain connection to database.",
				e);
		}
	}

	/**
	 * Close a result set
	 */
	public static void close(ResultSet results) {
		try {
			if (results != null)
				results.close();
		} catch (SQLException exception) {
		}
	}

	/**
	 * Close a connection
	 */
	public static void close(Connection connection) {
		try {
			if (connection != null)
				connection.close();
		} catch (SQLException exception) {
		}
	}

	/**
	 * Close a prepared statement
	 */
	public static void close(PreparedStatement stmt) {
		try {
			if (stmt != null)
				stmt.close();
		} catch (SQLException exception) {
		}
	}

	/**
	 * Close all resources
	 */
	public static void close(
		Connection connection,
		PreparedStatement stmt,
		ResultSet results) {
		close(results);
		close(stmt);
		close(connection);
	}

	/**
	 * Substitute prepared stmt query parameters
	 * @param stmt
	 * @param params
	 */
	public static void substitute(PreparedStatement stmt, Object[] params)
		throws SQLException {
		for (int i = 0; i < params.length; ++i) {

			stmt.setObject(i + 1, params[i]);
		}
	}

}
